<?php
class Itvina_JQuery_Form_Element_AutoComplete extends ZendX_JQuery_Form_Element_AutoComplete
{
	protected $_i_source;
	protected $_i_condition;

	public function __construct($spec, $options = null)
	{
		if (is_array ( $options ))
		{
			$this->fillSource ( $options );
		}
		unset ( $options ['i_source'], $options ['i_condition'] );
		parent::__construct ( $spec, $options );
	}

	public function fillSource($options = array())
	{
		if (is_array ( $options ))
		{
			if (array_key_exists ( 'i_source', $options ) && array_key_exists ( 'i_condition', $options ))
			{
				$this->_i_condition = $options ['i_condition'];
				$this->_i_source = Itvina_Model_Abstract::toArray2 ( $options ['i_source'], null, $options ['i_condition'] );
				
				$this->setJQueryParams ( array ('source' => $this->_i_source ) );
			}
		}
	}

	public function init()
	{
		//lấy tham số
		$id = $this->getId ();
		$name = $this->getName ();
		$value = $this->getValue ();
		
		$description=$this->getDescription ();
		$description.="<input type='hidden' id='hidden_$id' name='$name' value='$value' />";
		$this->setDescription ( $description );
		//$this->addDecorator ( 'Description', array ('escape' => false, 'tag' => '' ) );
		$this->setAttrib ( 'class', 'i-ui-autocomplete-input' );
		
		//Javascript
		//Events
		$create_script = "
			function (event, ui){
			
				//Giu lai gia tri cho the hidden...
				$('#hidden_$id').val( $(this).val() );
				
				//Huy ten cua doi tuong...	
				$(this).removeAttr('name');
				
				//Tao mang source javascript
				var source = $(this).autocomplete( 'option', 'source' );
				var data = new Array();
				for (var i = 0; i < source.length; i++){
					data[ source[i] ] = source[i];
				}
				$.data ( this, 'i-autocomplete', data );
		 	}
	 	";
		
		//Methods
		$select_script = "
			function (event, ui){
				var value = ui.item.value;			
				if ( value.indexOf(' - ') >= 0 ){
					value = value.split(' - ')[0];
				}
				$('#hidden_$id').val(value);
		 	}
	 	";
		$change_script = "function (event, ui){ if ( !($(this).val() in $.data ( this, 'i-autocomplete' )) ){ $(this).val(''); $('#hidden_$id').val(''); } }";
		
		$this->setJQueryParams ( array (//options
		'autoFocus' => true, 'delay' => 0, 

		//events
		'create' => new Zend_Json_Expr ( $create_script ), 

		//methods
		'select' => new Zend_Json_Expr ( $select_script ), 'change' => new Zend_Json_Expr ( $change_script ) ) );
	}

	//Overwrite setDescription
/*
    public function setDescription($description)
    {
        $this->_description = (string) $description;
        return $this;
    }
    */
}